# coding:utf-8
import StringIO
import hashlib
import json
import logging
import datetime
from flask import Blueprint, render_template, request, session, make_response, current_app, redirect, url_for, g
import time

from ..utils.permissions import require_user, require_visitor
from ..utils.uploadsets import images, random_filename, process_question, avatars
from web import csrf
from web.forms import PayForm
from web.models import db, User, PayLog
from web.models.product import TouguProduct, ModalType
from web.utils import alipay
from web.utils.alipay import notify_verify
from web.utils.code2 import getCodePiture

bp = Blueprint('user', __name__)


@bp.route('/home', methods=['GET'])
@require_user
def home():
    return render_template('user/home.html')


@bp.route('/order', methods=['GET'])
def orders():
    orders = g.user.pay_logs
    order_count = orders.count()
    return render_template('user/order.html', orders=orders, order_count=order_count)


@bp.route('/pay', methods=['GET','POST'])
@require_user
def pay():
    """充值"""
    config = current_app.config
    form = PayForm()
    pay_logs = g.user.pay_logs
    if form.is_submitted():
        money = int(form.price.data)
        hash_code = hashlib.md5()
        hash_code.update(str(time.time()))
        out_trade_no = hash_code.hexdigest()
        pay_log = PayLog(out_trade_no=out_trade_no, user_id=g.user.id, money=money)
        db.session.add(pay_log)
        db.session.commit()
        # title = u'支付（ %d 元）' % int(money)
        # payurl = alipay.create_direct_pay_by_user(out_trade_no, title, u'充值 %d 元' % money, money)
        payurl='https://shenghuo.alipay.com/send/payment/taobaoSellerFill.htm?nickName=yiditushe&payAmount=128.00&title={}&memo={}'
        payurl = "/user/to_pay"
        return redirect(payurl)
    order_id = int(request.args.get("order_id", 0))
    order = PayLog.query.get(order_id)
    money = order.money
    out_trade_no = order.out_trade_no
    title = u'支付（ %d 元）' % int(money)
    payurl = alipay.create_direct_pay_by_user(out_trade_no, title, u'充值 %d 元' % money, money)
    return redirect(payurl)


@bp.route('/to_pay', methods=['GET','POST'])
@require_user
def to_pay():
    price="100000"
    return render_template('user/to_pay.html',price=price)
@csrf.exempt
@bp.route('/alipay_notify', methods=['POST'])
def alipay_notify():
    logger = logging.getLogger()
    logger.info('----------alipay_notify----------')
    # 解码并验证数据是否有效
    if notify_verify(request.form):
        out_trade_no = request.form.get('out_trade_no')
        trade_no = request.form.get('trade_no')
        trade_status = request.form.get('trade_status')

        # 记录一条日志
        logger.info(out_trade_no + ',' + trade_no + ',' + trade_status)

        pay_log = PayLog.query.filter(PayLog.out_trade_no == out_trade_no).first()
        logger.info(pay_log)
        if pay_log.trade_status and pay_log.trade_status in ('TRADE_FINISHED', 'TRADE_SUCCESS'):
            logger.info('trade success.')
            pass
        else:
            month = pay_log.month
            pay_log.trade_no = trade_no
            pay_log.trade_status = trade_status
            db.session.add(pay_log)
            # 延后用户的exipre_time
            user_id = pay_log.user_id
            user = User.query.filter(User.id == user_id).first()

            if user.teacher.expired:
                user.teacher.expire_time = datetime.datetime.now() + datetime.timedelta(30 * month)
            else:
                user.teacher.expire_time += datetime.timedelta(30 * month)
            db.session.add(user)
            db.session.commit()
            logger.info('trade success.')
        # 有效数据需要返回 'success' 给 alipay
        return 'success'
        # 无效数据返回 'fail'
        # return 'fail'


@bp.route('/alipay_return', methods=['GET'])
def alipay_return():
    # 解码并验证数据是否有效
    if notify_verify(request.args):
        out_trade_no = request.args.get('out_trade_no')
        trade_no = request.args.get('trade_no')
        trade_status = request.args.get('trade_status')

        pay_log = PayLog.query.filter(PayLog.out_trade_no == out_trade_no).first()
        if pay_log.trade_status and pay_log.trade_status in ('TRADE_FINISHED', 'TRADE_SUCCESS'):
            pass
        else:
            month = pay_log.month
            pay_log.trade_no = trade_no
            pay_log.trade_status = trade_status
            db.session.add(pay_log)
            # 延后用户的exipre_time
            user_id = pay_log.user_id
            user = User.query.filter(User.id == user_id).first()

            if user.teacher.expired:
                user.teacher.expire_time = datetime.datetime.now() + datetime.timedelta(30 * month)
            else:
                user.teacher.expire_time += datetime.timedelta(30 * month)
            db.session.add(user)
            db.session.commit()

        return redirect(url_for('user.pay'))
    # 无效数据返回 'fail'
    return redirect(url_for('user.pay'))
